package com.lc.luzhengtang.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.AuthTask;
import com.lc.luzhengtang.BaseApplication;
import com.lc.luzhengtang.R;
import com.lc.luzhengtang.adapter.ConfirmListAdapter2;
import com.lc.luzhengtang.base.BaseActivity;
import com.lc.luzhengtang.bean.CommenBean;
import com.lc.luzhengtang.bean.OrderDetailBean;
import com.lc.luzhengtang.conn.ConnCancelOrder;
import com.lc.luzhengtang.conn.ConnOrderDetail;
import com.lc.luzhengtang.conn.ConnPay;
import com.lc.luzhengtang.conn.ConnSubmitShouhuo;
import com.lc.luzhengtang.interfaces.NoticeActivity;
import com.lc.luzhengtang.util.AuthResult;
import com.lc.luzhengtang.util.LovelyToast;
import com.lc.luzhengtang.util.OrderInfoUtil2_0;
import com.lc.luzhengtang.util.PayResult;
import com.lc.luzhengtang.util.WxPay;
import com.zcx.helper.http.AsyCallBack;
import com.zcx.helper.scale.ScaleScreenHelperFactory;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;


/**
 * Created by Administrator on 2017/6/12.
 */
public class OrderDetailActivity2 extends BaseActivity {


    ConfirmListAdapter2 confirmListAdapter;

    @BindView(R.id.img_news)
    ImageView imgNews;
    @BindView(R.id.layout_title)
    RelativeLayout layoutTitle;
    @BindView(R.id.text_wulaoer)
    TextView textWulaoer;
    @BindView(R.id.text_tel)
    TextView textTel;
    @BindView(R.id.rv_list)
    RecyclerView rvList;
    List<OrderDetailBean.DataBean.GoodsBean> confirmlist;
    @BindView(R.id.text_address)
    TextView textAddress;
    @BindView(R.id.btn_wuliu)
    Button btnWuliu;
    @BindView(R.id.btn_submit_shouhuo)
    Button btnSubmitShouhuo;
    @BindView(R.id.text_shop)
    TextView textShop;
    @BindView(R.id.text_cost)
    TextView textCost;

    @BindView(R.id.text_apy)
    TextView textApy;
    @BindView(R.id.text_content)
    TextView textContent;
    @BindView(R.id.text_order_sent)
    TextView textOrderSent;
    @BindView(R.id.text_order_time)
    TextView textOrderTime;
    @BindView(R.id.text_pay_status)
    TextView textPayStatus;
    public String ordersn;
    @BindView(R.id.text_youhui)
    TextView textYouhui;
    public static final String RSA_PRIVATE = "MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAJVxm7ggLNGRIY3Yt3xoZjrwMzTBCYqM/6X0MiHTds0Ba81dP7LnEBG8tBnc9NV2zWPCOXdPnrN7iGuWxC70C0fhbRPARDRUrbUZqExIeF6UDr6SumGIZZsLoQYobtZxfMXQAQaSgB6/ejbwqY1saHwo7AbG3nMXT7N8m+4p4V0ZAgMBAAECgYBtms88scxtP2Y+pI2eXutrmrPToyieR19QldMW4AMnxD0Od6+6RKGSgLYOqfGfheyJl++RxAF/XcDmN8NXNIH4ZovJLaxLGh44bG9d2MGAApBFbWLM4ZiJ9uK5KyIYztDuYkEicBkHGSe6YtNMe3lX3cTMPMPpHTyODRWitQI7SQJBAPK5eFQf8CXWRZtvv7cwdRjwY4/SGh4Fh25ZwUeizn4/EnZl/XMmYnLVdhQn6sFo5YxC4FJD3vRD0pvXu5lrUNsCQQCdng8+plLI4k7v3lB32Oyv1Xwu/q3CDh9QN9AMKk/5aPD/YrQ9mC6VfQNb5UR30P0/t+SAIOa5/3j9opH4lGIbAkEAjxnF1WMXBFe1phRWJTyObOuc5zfpafW8iNSl3QQhVdD9o4wxxufEdwtemDeIcgrT+sOa2SVmlwA9dN/VnHfmrQJAU+JuHJqqTm1bM3/u9YnGleIZoG08jp2zfp7lo8PVIlj+gfzHDkzy5e5NnlfLc7UPQx0ciDB6ex0DCIHADDr0ZwJBAO4ooeZitqD10l6p7pgP2qz+BYyug+/wJHNpZ2dF12Jp8m6KpD46XK6AvzyOT3HXEoQOmtMABBPktUfEHBELR/A=";
    public static final String APPID = "2017051007189568";
    public static final String RSA2_PRIVATE = "";
    private static final int SDK_PAY_FLAG = 1;
    private static final int SDK_AUTH_FLAG = 2;

    String status;
    @BindView(R.id.btn_wuliu2)
    Button btnWuliu2;
    @BindView(R.id.btn_submit_shouhuo2)
    Button btnSubmitShouhuo2;
    @BindView(R.id.btn_comment)
    Button btnComment;
    @BindView(R.id.btn_cancelorder)
    Button btnCancelorder;
    @BindView(R.id.btn_pay)
    Button btnPay;
    @BindView(R.id.layout_btn)
    LinearLayout layoutBtn;
    @BindView(R.id.text_cancel_order)
    TextView textCancelOrder;
    private PopupWindow popWindow, popWindow2;
    private PopupWindow popWindow3;

    private PopupWindow popWindow4;
    List<OrderDetailBean.DataBean.AddressBean> orderList = new ArrayList<>();

    List<OrderDetailBean.DataBean.GoodsBean> goodsBeanList = new ArrayList<>();

    List<Integer> idslist = new ArrayList<>();

    String moneypay;


    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        popWindow.dismiss();
                        ((com.lc.luzhengtang.interfaces.NoticeActivity<Integer>) OrderDetailActivity2.this).onRefresh(1);

                    } else {
                        finish();
                    }
                    break;
                }
                case SDK_AUTH_FLAG: {
                    @SuppressWarnings("unchecked")
                    AuthResult authResult = new AuthResult((Map<String, String>) msg.obj, true);
                    String resultStatus = authResult.getResultStatus();
                    ((NoticeActivity<Integer>) OrderDetailActivity2.this).onRefresh(0);
                    // 判断resultStatus 为“9000”且result_code
                    // 为“200”则代表授权成功，具体状态码代表含义可参考授权接口文档
                    if (TextUtils.equals(resultStatus, "9000") && TextUtils.equals(authResult.getResultCode(), "200")) {
                        // 获取alipay_open_id，调支付时作为参数extern_token 的value
                        // 传入，则支付账户为该授权账户
                       /* Toast.makeText(getActivity(),
                                "授权成功\n" + String.format("authCode:%s", authResult.getAuthCode()), Toast.LENGTH_SHORT)
                                .show();*/
                    } else {
                        // 其他状态值则为授权失败
                      /*  Toast.makeText(getActivity(),
                                "授权失败" + String.format("authCode:%s", authResult.getAuthCode()), Toast.LENGTH_SHORT).show();
*/
                    }
                    break;

                }
                default:
                    break;
            }
        }

        ;
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_confirmorder2);
        ButterKnife.bind(this);
        confirmlist = new ArrayList<>();
        rvList.setLayoutManager(new LinearLayoutManager(this));
        rvList.setNestedScrollingEnabled(false);
        ordersn = getIntent().getStringExtra("ordersn");
        status = getIntent().getStringExtra("status");
        idslist = getIntent().getIntegerArrayListExtra("stringList");
        if (status.equals("1")) {
            //申请退货
            btnWuliu.setVisibility(View.GONE);
            //申请退款
            btnSubmitShouhuo.setVisibility(View.GONE);
            //取消订单
            btnCancelorder.setVisibility(View.VISIBLE);
            //去支付
            btnPay.setVisibility(View.VISIBLE);
            //物流跟踪
            btnWuliu2.setVisibility(View.GONE);
            //确认收货
            btnSubmitShouhuo2.setVisibility(View.GONE);
            //去评价
            btnComment.setVisibility(View.GONE);

        } else if (status.equals("2")) {

            //申请退货
            btnWuliu.setVisibility(View.GONE);
            //申请退款
            btnSubmitShouhuo.setVisibility(View.VISIBLE);
            //取消订单
            btnCancelorder.setVisibility(View.GONE);
            //去支付
            btnPay.setVisibility(View.GONE);
            //物流跟踪
            btnWuliu2.setVisibility(View.GONE);
            //确认收货
            btnSubmitShouhuo2.setVisibility(View.GONE);
            //去评价
            btnComment.setVisibility(View.GONE);

        } else if (status.equals("3")) {
            //申请退货
            btnWuliu.setVisibility(View.GONE);
            //申请退款
            btnSubmitShouhuo.setVisibility(View.GONE);
            //取消订单
            btnCancelorder.setVisibility(View.GONE);
            //去支付
            btnPay.setVisibility(View.GONE);
            //物流跟踪
            btnWuliu2.setVisibility(View.VISIBLE);
            //确认收货
            btnSubmitShouhuo2.setVisibility(View.VISIBLE);
            //去评价
            btnComment.setVisibility(View.GONE);

        } else if (status.equals("4")) {
            //申请退货
            btnWuliu.setVisibility(View.GONE);
            //申请退款
            btnSubmitShouhuo.setVisibility(View.GONE);
            //取消订单
            btnCancelorder.setVisibility(View.GONE);
            //去支付
            btnPay.setVisibility(View.GONE);
            //物流跟踪
            btnWuliu2.setVisibility(View.GONE);
            //确认收货
            btnSubmitShouhuo2.setVisibility(View.GONE);
            //去评价
            btnComment.setVisibility(View.VISIBLE);
        } else if (status.equals("5")) {
            //申请退货
            btnWuliu.setVisibility(View.GONE);
            //申请退款
            btnSubmitShouhuo.setVisibility(View.GONE);
            //取消订单
            btnCancelorder.setVisibility(View.GONE);
            //去支付
            btnPay.setVisibility(View.GONE);
            //物流跟踪
            btnWuliu2.setVisibility(View.VISIBLE);
            //确认收货
            btnSubmitShouhuo2.setVisibility(View.VISIBLE);
            //去评价
            btnComment.setVisibility(View.GONE);
            layoutBtn.setVisibility(View.GONE);
        } else if (status.equals("7")) {
            //申请退货
            btnWuliu.setVisibility(View.GONE);
            //申请退款
            btnSubmitShouhuo.setVisibility(View.GONE);
            //取消订单
            btnCancelorder.setVisibility(View.GONE);
            //去支付
            btnPay.setVisibility(View.GONE);
            //物流跟踪
            btnWuliu2.setVisibility(View.VISIBLE);
            //确认收货
            btnSubmitShouhuo2.setVisibility(View.VISIBLE);
            //去评价
            btnComment.setVisibility(View.GONE);
        } else {
            //申请退货
            btnWuliu.setVisibility(View.GONE);
            //申请退款
            btnSubmitShouhuo.setVisibility(View.GONE);
            //取消订单
            btnCancelorder.setVisibility(View.GONE);
            //去支付
            btnPay.setVisibility(View.GONE);
            //物流跟踪
            btnWuliu2.setVisibility(View.GONE);
            //确认收货
            btnSubmitShouhuo2.setVisibility(View.GONE);
            //去评价
            btnComment.setVisibility(View.GONE);
        }
//        ids=getIntent().getStringExtra("cart_id");
        //购物车id

        getOrderData();
    }


    public void getOrderData() {
        new ConnOrderDetail(BaseApplication.basePreferences.readUid(), getIntent().getStringExtra("ordersn"), new AsyCallBack<OrderDetailBean>() {
            @Override
            public void onStart(int type) throws Exception {
                super.onStart(type);
            }

            @Override
            public void onSuccess(String toast, int type, Object o, OrderDetailBean orderDetailBean) throws Exception {
                super.onSuccess(toast, type, o, orderDetailBean);
                ordersn = getIntent().getStringExtra("ordersn");
                confirmlist = orderDetailBean.getData().getGoods();


                //传订单ID
                orderList = orderDetailBean.getData().getAddress();
                //传图片的URL
                goodsBeanList = orderDetailBean.getData().getGoods();

                confirmListAdapter = new ConfirmListAdapter2(confirmlist);
//地址啥玩意的乱七八糟的
                textWulaoer.setText(orderDetailBean.getData().getAddress().get(0).getUsername());
                textTel.setText(orderDetailBean.getData().getAddress().get(0).getMobile());
                textAddress.setText(orderDetailBean.getData().getAddress().get(0).getAddress());
                rvList.setAdapter(confirmListAdapter);


                //运费text_cost
                textCost.setText("¥" + orderDetailBean.getData().getAddress().get(0).getPostcost() + "");


                textYouhui.setText("-" + "¥" + orderDetailBean.getData().getAddress().get(0).getDiscount());
//实付金额text_apy
                textApy.setText("¥" + orderDetailBean.getData().getAddress().get(0).getTotal());
                //商品金额text_shop
                textShop.setText("¥" + orderDetailBean.getData().getAddress().get(0).getGoodsmoney() + "");
                moneypay = orderDetailBean.getData().getAddress().get(0).getGoodsmoney();
                //买家留言text_content
                textContent.setText(orderDetailBean.getData().getAddress().get(0).getContent());
                //订单编号text_order_sent
                textOrderSent.setText(orderDetailBean.getData().getAddress().get(0).getOrdersn());
                //下单时间 text_order_time
                textOrderTime.setText(orderDetailBean.getData().getAddress().get(0).getCreate_time());
                //支付方式 text_pay_status
                if (orderDetailBean.getData().getAddress().get(0).getPaytype().equals("0")) {
                    textPayStatus.setText("未支付");
                    textCancelOrder.setVisibility(View.GONE);
                } else if (orderDetailBean.getData().getAddress().get(0).getPaytype().equals("1")) {
                    textPayStatus.setText("余额");
                    textCancelOrder.setVisibility(View.GONE);
                } else if (orderDetailBean.getData().getAddress().get(0).getPaytype().equals("2")) {
                    textPayStatus.setText("微信");
                    textCancelOrder.setVisibility(View.GONE);
                } else if (orderDetailBean.getData().getAddress().get(0).getPaytype().equals("3")) {
                    textPayStatus.setText("支付宝");
                    textCancelOrder.setVisibility(View.GONE);
                } else if (orderDetailBean.getData().getAddress().get(0).getPaytype().equals("4")) {
                    textPayStatus.setText("线下付款");
                    textCancelOrder.setVisibility(View.VISIBLE);
                    btnPay.setVisibility(View.GONE);
                }


            }

            @Override
            public void onFail(String toast, int type) throws Exception {
                super.onFail(toast, type);
            }

            @Override
            public void onEnd(String toast, int type) throws Exception {
                super.onEnd(toast, type);
            }
        }

        ).execute(OrderDetailActivity2.this, false);
    }


    @OnClick({R.id.img_news, R.id.layout_title, R.id.text_wulaoer, R.id.text_tel, R.id.btn_submit_shouhuo, R.id.btn_wuliu2, R.id.btn_submit_shouhuo2, R.id.btn_comment, R.id.btn_cancelorder, R.id.btn_pay})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.img_news:
                finish();
                break;
            case R.id.layout_title:
                break;
            case R.id.text_wulaoer:
                break;
            case R.id.text_tel:
                break;
            case R.id.btn_submit_shouhuo:
                //跳转到退款界面
                Intent intent = new Intent();
                intent.putExtra("ordersn", ordersn);
                intent.setClass(OrderDetailActivity2.this, RefundActivity.class);

                startActivity(intent);
                OrderAllActivity.instance.finish();
                finish();
                break;
            case R.id.btn_wuliu2:
                Intent intent2 = new Intent();

                intent2.putExtra("url", getIntent().getStringExtra("weburl"));
                intent2.setClass(OrderDetailActivity2.this, WuliuActivity.class);
                startActivity(intent2);

                break;
            case R.id.btn_submit_shouhuo2:
                showPopupWindow3(btnSubmitShouhuo2);
                break;

            case R.id.btn_comment:
//                Intent intent1=new Intent();
                final ArrayList<Integer> idList = new ArrayList<>();
                final ArrayList<String> picList = new ArrayList<>();
//
                for (int i = 0; i < goodsBeanList.size(); i++) {
                    picList.add(goodsBeanList.get(i).getPicurl());
                }

                Intent intent1 = new Intent(OrderDetailActivity2.this, EvaluateActivity.class);
                Bundle bundle = new Bundle();
                bundle.putIntegerArrayList(EvaluateActivity.KEY_IDS, (ArrayList<Integer>) idslist);
                bundle.putStringArrayList(EvaluateActivity.KEY_PICS, picList);
                bundle.putString(EvaluateActivity.KEY_ORDERSN, ordersn);
                intent1.putExtras(bundle);
                startActivity(intent1);
                finish();
                break;
//取消订单
            case R.id.btn_cancelorder:
                showPopupWindow2(view);

                break;
            //去付款
            case R.id.btn_pay:

                showPopupWindow4(btnPay);


                break;

        }
    }

    private void showPopupWindow2(View parent) {
        if (popWindow2 == null) {
    /*        View view = BoundViewHelper.boundView(this, MyApplication.scaleScreenHelper.loadView((ViewGroup) LayoutInflater.from(this)
                    .inflate(R.layout.dialog_01, null)));*/
//            ScaleScreenHelperFactory.getInstance().loadView((ViewGroup) convertView);
            View view2 = ScaleScreenHelperFactory.getInstance().loadView((ViewGroup) LayoutInflater.from(OrderDetailActivity2.this).inflate(R.layout.dialog_01, null));

            //LayoutParams相当于一个Layout的信息包，它封装了Layout的位置、高、宽等信息。
            popWindow2 = new PopupWindow(view2, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT, true);
            initPop2(view2);
        }
        //设置动画效果
        popWindow2.setAnimationStyle(android.R.style.Animation_Dialog);
        //获取popwindow焦点
        popWindow2.setFocusable(true);
        //设置popwindow如果点击外面区域，便关闭。
        popWindow2.setOutsideTouchable(true);
        popWindow2.setBackgroundDrawable(new BitmapDrawable());
        //实现软键盘不自动弹出,ADJUST_RESIZE属性表示Activity的主窗口总是会被调整大小，从而保证软键盘显示空间。
        popWindow2.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        //设置popwindow显示位置
        popWindow2.showAtLocation(parent, Gravity.CENTER, 0, 0);
    }

    public void initPop2(View view) {
        TextView tv01 = (TextView) view.findViewById(R.id.dl_tv_01);//拍照
        TextView tv02 = (TextView) view.findViewById(R.id.dl_tv_02);//相册

        TextView text_cadncel = (TextView) view.findViewById(R.id.text_cadncel);
        text_cadncel.setText("是否取消订单");
        tv01.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {

                popWindow2.dismiss();

            }

        });
        tv02.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                popWindow2.dismiss();

                new ConnCancelOrder(getIntent().getStringExtra("order_id"), new AsyCallBack<CommenBean>() {
                    @Override
                    public void onStart(int type) throws Exception {
                        super.onStart(type);
                    }

                    @Override
                    public void onSuccess(String toast, int type, Object o, CommenBean commenBean) throws Exception {
                        super.onSuccess(toast, type, o, commenBean);
                        LovelyToast.makeText(OrderDetailActivity2.this, commenBean.getMessage(), 0, LovelyToast
                                .SUCCESS, LovelyToast.SCALE);
                        finish();
                    }

                    @Override
                    public void onFail(String toast, int type) throws Exception {
                        super.onFail(toast, type);
                    }

                    @Override
                    public void onEnd(String toast, int type) throws Exception {
                        super.onEnd(toast, type);
                    }
                }


                ).execute(OrderDetailActivity2.this, false);

                popWindow2.dismiss();


            }
        });
    }


    private void showPopupWindow3(View parent) {
        if (popWindow3 == null) {
    /*        View view = BoundViewHelper.boundView(this, MyApplication.scaleScreenHelper.loadView((ViewGroup) LayoutInflater.from(this)
                    .inflate(R.layout.dialog_01, null)));*/
//            ScaleScreenHelperFactory.getInstance().loadView((ViewGroup) convertView);
            View view = ScaleScreenHelperFactory.getInstance().loadView((ViewGroup) LayoutInflater.from(OrderDetailActivity2.this).inflate(R.layout.dialog_01, null));

            //LayoutParams相当于一个Layout的信息包，它封装了Layout的位置、高、宽等信息。
            popWindow3 = new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT, true);
            initPop3(view);
        }
        //设置动画效果
        popWindow3.setAnimationStyle(android.R.style.Animation_Dialog);
        //获取popwindow焦点
        popWindow3.setFocusable(true);
        //设置popwindow如果点击外面区域，便关闭。
        popWindow3.setOutsideTouchable(true);
        popWindow3.setBackgroundDrawable(new BitmapDrawable());
        //实现软键盘不自动弹出,ADJUST_RESIZE属性表示Activity的主窗口总是会被调整大小，从而保证软键盘显示空间。
        popWindow3.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        //设置popwindow显示位置
        popWindow3.showAtLocation(parent, Gravity.CENTER, 0, 0);
    }


    public void initPop3(View view) {
        TextView tv01 = (TextView) view.findViewById(R.id.dl_tv_01);//拍照
        TextView tv02 = (TextView) view.findViewById(R.id.dl_tv_02);//相册

        TextView text_cadncel = (TextView) view.findViewById(R.id.text_cadncel);
        text_cadncel.setText("是否确认收货");
        tv01.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                popWindow3.dismiss();

            }

        });
        tv02.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                popWindow3.dismiss();
                new ConnSubmitShouhuo(ordersn, new AsyCallBack<CommenBean>() {

                    @Override
                    public void onSuccess(String toast, int type, Object o, CommenBean commenBean) throws Exception {
                        super.onSuccess(toast, type, o, commenBean);
//                                Toast.makeText(getActivity(), "确认收货成功", Toast.LENGTH_SHORT).show();

                        if (commenBean.getCode() == 200) {
                            LovelyToast.makeText(OrderDetailActivity2.this, "确认收货成功", 0, LovelyToast
                                    .SUCCESS, LovelyToast.SCALE);
                            finish();
                        } else {
                            LovelyToast.makeText(OrderDetailActivity2.this, commenBean.getMessage(), 0, LovelyToast
                                    .SUCCESS, LovelyToast.SCALE);
                        }

                    }

                    @Override
                    public void onFail(String toast, int type) throws Exception {
                        super.onFail(toast, type);

                    }

                    @Override
                    public void onEnd(String toast, int type) throws Exception {
                        super.onEnd(toast, type);

                    }
                }

                ).execute(OrderDetailActivity2.this, false);


                popWindow3.dismiss();


            }
        });
    }


    private void showPopupWindow4(View parent) {
        if (popWindow4 == null) {
    /*        View view = BoundViewHelper.boundView(this, MyApplication.scaleScreenHelper.loadView((ViewGroup) LayoutInflater.from(this)
                    .inflate(R.layout.dialog_01, null)));*/
//            ScaleScreenHelperFactory.getInstance().loadView((ViewGroup) convertView);
            View view = ScaleScreenHelperFactory.getInstance().loadView((ViewGroup) LayoutInflater.from(OrderDetailActivity2.this).inflate(R.layout.dialog_fukuan, null));

            //LayoutParams相当于一个Layout的信息包，它封装了Layout的位置、高、宽等信息。
            popWindow4 = new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT, true);
            initPop4(view);
        }
        //设置动画效果
        popWindow4.setAnimationStyle(android.R.style.Animation_Dialog);
        //获取popwindow焦点
        popWindow4.setFocusable(true);
        //设置popwindow如果点击外面区域，便关闭。
        popWindow4.setOutsideTouchable(true);
        popWindow4.setBackgroundDrawable(new BitmapDrawable());
        //实现软键盘不自动弹出,ADJUST_RESIZE属性表示Activity的主窗口总是会被调整大小，从而保证软键盘显示空间。
        popWindow4.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        //设置popwindow显示位置
        popWindow4.showAtLocation(parent, Gravity.CENTER, 0, 0);
    }

    private String paytype = "2";

    public void initPop4(View view) {
        LinearLayout layout_dismiss = (LinearLayout) view.findViewById(R.id.layout_dismiss);
        layout_dismiss.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popWindow4.dismiss();

                popWindow4 = null;
            }
        });
        LinearLayout layout_wx = (LinearLayout) view.findViewById(R.id.layout_wx);
        final ImageView img_wx = (ImageView) view.findViewById(R.id.img_wx);

        LinearLayout layout_alipay = (LinearLayout) view.findViewById(R.id.layout_alipay);
        final ImageView img_alipay = (ImageView) view.findViewById(R.id.img_alipay);
        LinearLayout layout_yue = (LinearLayout) view.findViewById(R.id.layout_yue);
        final ImageView img_yue = (ImageView) view.findViewById(R.id.img_yue);
        LinearLayout layout_xianxia = (LinearLayout) view.findViewById(R.id.layout_xianxia);
        final ImageView img_offline = (ImageView) view.findViewById(R.id.img_offline);
        layout_wx.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                img_wx.setImageResource(R.mipmap.checkboxselected);
                img_alipay.setImageResource(R.mipmap.checkboxunselected);
                img_yue.setImageResource(R.mipmap.checkboxunselected);
                img_offline.setImageResource(R.mipmap.checkboxunselected);
//                popWindow.dismiss();
                paytype = "2";
            }
        });
        layout_alipay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                img_wx.setImageResource(R.mipmap.checkboxunselected);
                img_alipay.setImageResource(R.mipmap.checkboxselected);
                img_yue.setImageResource(R.mipmap.checkboxunselected);
                img_offline.setImageResource(R.mipmap.checkboxunselected);
//                popWindow.dismiss();
                paytype = "3";
            }
        });

        layout_yue.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                img_wx.setImageResource(R.mipmap.checkboxunselected);
                img_alipay.setImageResource(R.mipmap.checkboxunselected);
                img_yue.setImageResource(R.mipmap.checkboxselected);
                img_offline.setImageResource(R.mipmap.checkboxunselected);
                paytype = "1";
//                popWindow.dismiss();
            }
        });
        layout_xianxia.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                img_wx.setImageResource(R.mipmap.checkboxunselected);
                img_alipay.setImageResource(R.mipmap.checkboxunselected);
                img_yue.setImageResource(R.mipmap.checkboxunselected);
                img_offline.setImageResource(R.mipmap.checkboxselected);
//                popWindow.dismiss();
                paytype = "4";
            }
        });

        TextView text_balance = (TextView) view.findViewById(R.id.text_balance);
        text_balance.setText("（" + "¥" + BaseApplication.basePreferences.readBalance() + "）");

        TextView text_allmoney = (TextView) view.findViewById(R.id.text_allmoney);
        text_allmoney.setText("￥" + moneypay);
        Button submit_order = (Button) view.findViewById(R.id.submit_order);


        submit_order.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TextUtils.isEmpty(paytype)) {
                    LovelyToast.makeText(OrderDetailActivity2.this, "请选择支付方式", 0, LovelyToast
                            .SUCCESS, LovelyToast.SCALE);
                } else if (paytype.equals("1")) {
                    goPay();
                } else if (paytype.equals("4")) {
                    goPay();

                } else if (paytype.equals("3")) {
                    alipayData();
                } else {
                    WxPay wxPay = new WxPay(OrderDetailActivity2.this);

                    try {
                        double money = Double.parseDouble(moneypay) * 100;
                        wxPay.pay("清君堂", ordersn, subZeroAndDot(String.valueOf(money)), "3");
                        popWindow4.dismiss();
                        popWindow4 = null;
                    } catch (NumberFormatException e) {
                        e.printStackTrace();
                        Toast.makeText(OrderDetailActivity2.this, "数据加载失败", Toast.LENGTH_SHORT).show();
                        popWindow4.dismiss();
                        popWindow4 = null;
                    }

                }
//                goPay();
            }
        });
    }

    /**
     * 使用java正则表达式去掉多余的.与0
     *
     * @param s
     * @return
     */
    private String subZeroAndDot(String s) {
        if (s.indexOf(".") > 0) {
            s = s.replaceAll("0+?$", "");//去掉多余的0
            s = s.replaceAll("[.]$", "");//如最后一位是.则去掉
        }
        return s;
    }

    public void goPay() {

        new ConnPay(ordersn, paytype, new AsyCallBack<CommenBean>() {
            @Override
            public void onStart(int type) throws Exception {
                super.onStart(type);
            }

            @Override
            public void onSuccess(String toast, int type, Object o, CommenBean commenBean) throws Exception {
                super.onSuccess(toast, type, o, commenBean);
                if (commenBean.getCode() == 200) {
                    popWindow4.dismiss();

                    LovelyToast.makeText(OrderDetailActivity2.this, "付款成功", 0, LovelyToast
                            .SUCCESS, LovelyToast.SCALE);
                    Intent intent2 = new Intent();
                    intent2.putExtra("ids", "2");
                    intent2.putExtra("ordersn", ordersn);
                    intent2.setClass(OrderDetailActivity2.this, OrderAllActivity.class);
                    startActivity(intent2);
                    finish();


                } else {
                    LovelyToast.makeText(OrderDetailActivity2.this, commenBean.getMessage(), 0, LovelyToast
                            .SUCCESS, LovelyToast.SCALE);
                    startActivity(new Intent(OrderDetailActivity2.this, OrderAllActivity.class));
                    finish();
                }

            }

            @Override
            public void onFail(String toast, int type) throws Exception {
                super.onFail(toast, type);
            }

            @Override
            public void onEnd(String toast, int type) throws Exception {
                super.onEnd(toast, type);
            }

        }


        ).execute(OrderDetailActivity2.this, false);
    }


    public void alipayData() {

        /**
         * 这里只是为了方便直接向商户展示支付宝的整个支付流程；所以Demo中加签过程直接放在客户端完成；
         * 真实App里，privateKey等数据严禁放在客户端，加签过程务必要放在服务端完成；
         * 防止商户私密数据泄露，造成不必要的资金损失，及面临各种安全风险；
         *
         * orderInfo的获取必须来自服务端；
         */

        String name = "鹿正堂";

        String body = ordersn + "," + "0" + "," + "1" + "," + BaseApplication.basePreferences.readUid();
//        String body = BaseApplication.basePreferences.readUid();
        boolean rsa2 = false;
//        Map<String, String> authInfoMap = OrderInfoUtil2_0.buildOrderParamMap(APPID, rsa2, body, ordersn, num_shop, name);
        Map<String, String> authInfoMap = OrderInfoUtil2_0.buildOrderParamMap(APPID, rsa2, body, ordersn, moneypay, name);
        String info = OrderInfoUtil2_0.buildOrderParam(authInfoMap);

        String sign = OrderInfoUtil2_0.getSign(authInfoMap, ConfirmOrderActivity.RSA_PRIVATE, rsa2);
        final String authInfo = info + "&" + sign;
        Log.i("123456789", authInfo);
        Runnable authRunable = new Runnable() {
            @Override
            public void run() {
                // 构造PayTask对象
                AuthTask authTask = new AuthTask(OrderDetailActivity2.this);
                // 调用支付接口,获取支付结果
                Map<String, String> result = authTask.authV2(authInfo, true);
                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };
        // 必须异步调用
        Thread authThread = new Thread(authRunable);
        authThread.start();
    }
}
